//
//  MBSpaceMyCollectionShowViewController.m
//  MiBaoTu
//
//  Created by admin on 16/9/21.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBSpaceDownedMusicViewController.h"
#import "MBSpaceAddMusicViewController.h"
#import "MBSongDetailController.h"
#import "MBDetailViewController.h"
#import "MBSpaceAlbumViewController.h"
#import "MBSongDetailForIController.h"
#import "MBLoginController.h"

#import "MBSpaceCollectionMusicCell.h"
#import "MBSpaceCollectionCompileView.h"
#import "SharePLayerView.h"

#import "MBSongDetailForIpadController.h"
#import "MBDetailViewForIpadController.h"
@interface MBSpaceDownedMusicViewController ()<UITableViewDataSource,UITableViewDelegate,MBSpaceCollectionCompileViewDelegate,MBSpaceCollectionMusicCellDelegate,SharePLayerViewDelegate> {
    UITableView                             *_tableView;
    MBSpaceCollectionCompileView            *_compileView;
    NSMutableArray                          *_selectMusicArr;//保存选中的歌曲
    NSMutableArray                          *_downedMusicArr;
    NSMutableDictionary                     *_selectCurrentMusicDic;//选中当前的音频字典
    NSMutableArray                          *_fileIDArr;   //最近播放中已下载歌曲id
    MusicPLayType                           _musicPlayType;
}

@property (nonatomic,assign)BOOL isCompiling;//是否批量编译
@property (nonatomic,assign)BOOL isAllSelcting;//是否全选

@end

@implementation MBSpaceDownedMusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isCompiling = NO;
    self.isAllSelcting = NO;
    _selectCurrentMusicDic = [[NSMutableDictionary alloc]init];
    _selectMusicArr = [[NSMutableArray alloc]init];
    _downedMusicArr = [[NSMutableArray alloc]init];
    _fileIDArr = [[NSMutableArray alloc]init];
    // Do any additional setup after loading the view.
    [self setNavBar];
    [self onCreateUI];
    
    [self loadData];
}

#pragma mark - Actions
#pragma mark - UI
- (void)setNavBar
{
    if (self.type == MBSpaceDownedMusicType_Downed) {
        [self setTitleView:@"已下载"];
        _musicPlayType = MusicPLayType_DownedMusic;
    }
    else if (self.type == MBSpaceDownedMusicType_Visit) {
        [self setTitleView:@"最近播放"];
        _musicPlayType = MusicPLayType_RecentMusicPlay;
    }

    [self setBackItem];
    
    [self setRightPlayerItem];
}

- (void)onCreateUI
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    [self.view addSubview:_tableView];
    _tableView.tableHeaderView = [self setTableHeaderViewWithIndex:2];
    
    //批量弹出框
    _compileView = [[MBSpaceCollectionCompileView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 100*PERCEN) WithIndex:2];
    _compileView.delegate = self;
    _compileView.hidden = YES;
    [self.view addSubview:_compileView];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height);
    _tableView.tableHeaderView = [self setTableHeaderViewWithIndex:2];
    _compileView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 100*PERCEN);
    _compileView.orientation = self.orientation;
    [_tableView reloadData];
}

//增加的3个头部按钮 播放、批量、更多
- (UIView *)setTableHeaderViewWithIndex:(NSInteger)index
{
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120*PERCEN)];
    bgView.backgroundColor = [UIColor clearColor];
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, bgView.width, 100*PERCEN)];
    contentView.backgroundColor = [UIColor whiteColor];
    [bgView addSubview:contentView];
    
    float itemWidth = 20*PERCEN;
    float btWidth = 1.*(bgView.width-(index+1)*itemWidth)/index;
    if (ISIPAD) {
        itemWidth = 44*PERCEN;
        btWidth = 540*PERCEN;
    }
    for (int i=0; i<index; i++) {
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        bt.frame = CGRectMake(itemWidth+(btWidth+itemWidth)*i, 18*PERCEN, btWidth, 64*PERCEN);
        if (ISIPAD) {
            bt.left = (self.orientation==UIDeviceOrientationPortrait?(contentView.width-btWidth*index-itemWidth*(index-1))/2.:440*PERCEN)+(btWidth+44*PERCEN)*i;
        }
        bt.backgroundColor = [UIColor whiteColor];
        [bt setTitleColor:UIColorFromHex(0x333333) forState:UIControlStateNormal];
        bt.layer.cornerRadius = 6.f;
        bt.layer.masksToBounds = YES;
        bt.layer.borderColor = UIColorFromHex(0x999999).CGColor;
        bt.layer.borderWidth = 1;
        bt.tag = 1000+i;
        bt.titleLabel.font = [UIFont systemFontOfSize:13.];
        [bt addTarget:self action:@selector(onTapForMusicAction:) forControlEvents:UIControlEventTouchUpInside];
        [contentView addSubview:bt];
        
        if (i == 0) {
            [bt setTitle:@"播放全部" forState:UIControlStateNormal];
        }
        else if (i == 1) {
            [bt setTitle:@"批量操作" forState:UIControlStateNormal];
        }
        else if (i == 2) {
            [bt setTitle:@"更多" forState:UIControlStateNormal];
        }
    }
    
    return bgView;
}

#pragma mark - 获取数据
- (void)loadData
{
    if (self.type == MBSpaceDownedMusicType_Downed) {
        //已下载
        NSArray *musicDowningArr = [UserManager standerDefult].downedMusicArr;
        NSArray *downedQzixArr = [[FMManageObject standerDefault]onSelectLocalParentChildShowCount];
        if (musicDowningArr.count > 0) {
            [_downedMusicArr removeAllObjects];
            [_downedMusicArr addObjectsFromArray:musicDowningArr];
        }
        if (downedQzixArr.count > 0) {
            [_downedMusicArr addObjectsFromArray:downedQzixArr];
        }
    }
    else if (self.type == MBSpaceDownedMusicType_Visit) {
        NSArray *recentMusicArr = [[FMManageObject standerDefault]onSelectMusicPlayForRecent];
        if (recentMusicArr.count > 0) {
            [_downedMusicArr removeAllObjects];
            [_downedMusicArr addObjectsFromArray:recentMusicArr];
            
            [_fileIDArr removeAllObjects];
            NSArray *musicDowningArr = [UserManager standerDefult].downedMusicArr;
            NSArray *downedQzixArr = [[FMManageObject standerDefault]onSelectLocalParentChildShowCount];
            for (NSDictionary *dic in musicDowningArr) {
                NSString *idStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"fileID"]];
                [_fileIDArr addObject:idStr];
            }
            for (NSDictionary *dic in downedQzixArr) {
                NSString *idStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"musicId"]];
                if (![_fileIDArr containsObject:idStr]) {
                    [_fileIDArr addObject:idStr];
                }
            }
        }
    }
    
    [_tableView reloadData];
}

#pragma mark - 跳转播放器
- (void)onSelectItemForWork
{
    [self onPlayMusic];
}

#pragma mark - 播放全部、批量、更多
- (void)onTapForMusicAction:(UIButton *)bt
{
    switch (bt.tag-1000) {
        case 0:
        {
            //播放全部
            if (_downedMusicArr.count > 0) {
//                [[UserManager standerDefult]playMusicWithMusicArray:_downedMusicArr withCurrentIndex:0 withMusicPlayType:_musicPlayType];
                _selectCurrentMusicDic = [_downedMusicArr objectAtIndex:0];
                [self onSelctItemForMorePlayMusic:nil];
            }
        }
            break;
        case 1:
        {
            //批量
            self.isCompiling = !self.isCompiling;
            if (self.isCompiling) {
                //弹出批量框
                _tableView.height = self.view.height-_compileView.height;
                _compileView.top = _tableView.bottom;
                _compileView.hidden = NO;
            } else {
                //隐藏
                _tableView.height = self.view.height;
                _compileView.top = _tableView.bottom;
                _compileView.hidden = YES;
                self.isAllSelcting = NO; //不全选
                [_selectMusicArr removeAllObjects]; //删除所有选中的歌曲
            }
            //返回按钮改变
            [self onChangeBackButton:self.isCompiling];
            
            [_tableView reloadData];
        }
            break;
        case 2:
        {
            //更多
            //1.批量还原
            if (self.isCompiling) {
                UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
                [self onTapForMusicAction:bt];
            }
            //2,显示
            SharePLayerView *show = [[SharePLayerView alloc]initWithFrame:CGRectZero withType:ShowPlayerType_Moer];
            show.delegate = self;
            show.orientation = self.orientation;
            [show onShowInWindow];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 改变返回按钮样式
- (void)onChangeBackButton:(BOOL) compileStatus {
    if (compileStatus) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 60, 30);
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:14.]];
        [btn setTitle:@"全选" forState:UIControlStateNormal];
        [btn setTitle:@"全选" forState:UIControlStateHighlighted];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 25)];
        [btn addTarget:self action:@selector(onSelectTapAllMusicAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [self setLeftBarItem:btn];
        [self setRightBarItems:nil];
    } else {
        [self setBackItem];
        
        [self setRightPlayerItem];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 批量操作 取消、删除、收藏
- (void)onSelectItemForCancel:(MBSpaceCollectionCompileView *)view
{
    UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
    [self onTapForMusicAction:bt];
}
- (void)onSelectItemForDelete:(MBSpaceCollectionCompileView *)view
{
    if (_selectMusicArr.count > 0) {
        NSMutableArray *newArr = [[NSMutableArray alloc]initWithArray:_selectMusicArr];
        for (NSDictionary *dic in newArr) {
            NSUInteger index = [_downedMusicArr indexOfObject:dic];
            [_downedMusicArr removeObject:dic];
            [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            
            //同步
            FMManageObject *manager = [FMManageObject standerDefault];
            if (self.type == MBSpaceDownedMusicType_Downed) {
                NSFileManager *fileManager = [NSFileManager defaultManager];
                 if (![dic.allKeys containsObject:@"userPic"]) {
                     [manager deleteCunstomFileID:[dic objectForKey:@"fileID"]];
                     if ([fileManager fileExistsAtPath:[dic objectForKey:@"url"]]) {
                         [fileManager removeItemAtPath:[dic objectForKey:@"url"] error:NULL];
                     }
                     NSArray *musicArr = [manager onSelectCustomMusicFileCount];
                     [[UserManager standerDefult].downedMusicArr removeAllObjects];
                     [[UserManager standerDefult].downedMusicArr addObjectsFromArray:musicArr];
                 } else {
                     
                     [manager deleteByLocalParentChildShowFilID:[NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]]];
                     NSString *mp3Path = [dic objectForKey:@"mp3"];
                     if ([mp3Path isKindOfClass:[NSString class]]) {
                         if (mp3Path.length > 0) {
                             mp3Path = [[mp3Path componentsSeparatedByString:@"."]lastObject];
                             NSString *fileMp3Path = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"qzx_%@.%@",[dic objectForKey:@"title"],mp3Path]];
                             if ([fileManager fileExistsAtPath:fileMp3Path]) {
                                 [fileManager removeItemAtPath:fileMp3Path error:NULL];
                             }
                         }
                     }
                 }
                
            }
            else if (self.type == MBSpaceDownedMusicType_Visit) {
                [manager deleteByMusicPlayForRecentFileID:[dic objectForKey:@"fileID"]];
            }
        }
    }
    
    [_selectMusicArr removeAllObjects];
    if (_downedMusicArr.count == 0) {
        //已下载歌曲删除完
        UIButton *bt = (UIButton *)[self.view viewWithTag:1001];
        [self onTapForMusicAction:bt];
    }
}
- (void)onSelectItemForNoCollection:(MBSpaceCollectionCompileView *)view
{
    
}

#pragma mark - 勾选一首歌曲
- (void)onSelectItemForGouXuanWithValue:(NSDictionary *)value WithSelect:(BOOL)isSelect WithView:(MBSpaceCollectionMusicCell *)view
{
    //数据保存
    NSLog(@"数据是否需要保存:%d",isSelect);
    if (isSelect) {
        //保存
        [_selectMusicArr addObject:value];
    } else {
        //删除
        if ([_selectMusicArr containsObject:value]) {
            [_selectMusicArr removeObject:value];
        }
    }
    
    //删除、收藏是否可选中
    [_compileView onUpdateDataForDelegateAndCollection:(_selectMusicArr.count > 0 ? YES : NO)];
    
    if (_selectMusicArr.count != _downedMusicArr.count) {
        //不相等 显示全选
        [self onChangeBackButton:YES];
    }
}


#pragma mark - 全选
- (void)onSelectAllMusicAction:(BOOL)isAllSelect
{
    self.isAllSelcting = isAllSelect;
    
    //测试
    [_selectMusicArr removeAllObjects];
    if (isAllSelect) {
        [_selectMusicArr addObjectsFromArray:_downedMusicArr];
    }
    
    //删除、收藏是否可选中
    [_compileView onUpdateDataForDelegateAndCollection:(_selectMusicArr.count > 0 ? YES : NO)];
    
    [_tableView reloadData];
}

//全选
- (void)onSelectTapAllMusicAction:(UIButton *)bt
{
    bt.selected = !bt.selected;
    if (bt.selected) {
        [bt setTitle:@"全不选" forState:UIControlStateNormal];
        [bt setTitle:@"全不选" forState:UIControlStateHighlighted];
        [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
    } else {
        [bt setTitle:@"全选" forState:UIControlStateNormal];
        [bt setTitle:@"全选" forState:UIControlStateHighlighted];
        [bt setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 25)];
    }
    [self onSelectAllMusicAction:bt.selected];
}

#pragma mark - 更多操作 添加歌曲、播放、分享、取消收藏、下载
//添加歌曲
- (void)onSelctItemForMoreAddMusic:(SharePLayerView *)view
{
//    MBSpaceAddMusicViewController *addMusic = [[MBSpaceAddMusicViewController alloc]init];
//    addMusic.type = MBSpaceAddMusicType_SetAlbum;
//    addMusic.albumName = @"分类";
//    [self.navigationController pushViewController:addMusic animated:YES];
}

//每个歌曲更多操作
- (void)onSelectItemForMoewWithValue:(NSDictionary *)value withView:(MBSpaceCollectionMusicCell *)view
{
    if (value) {
        [_selectCurrentMusicDic removeAllObjects];
        [_selectCurrentMusicDic addEntriesFromDictionary:value];
        
        SharePLayerView *show = [[SharePLayerView alloc]initWithFrame:CGRectZero withType:ShowPlayerType_DownMusic];
        show.delegate = self;
        show.orientation = self.orientation;
        [show onShowInWindow];
    }
}

//播放
- (void)onSelctItemForMorePlayMusic:(SharePLayerView *)view
{

    NSString *type = [_selectCurrentMusicDic objectForKey:@"type"];
    NSMutableArray *newMusicArr = [[NSMutableArray alloc]init];
    UserManager *manager = [UserManager standerDefult];
    
    if ([type intValue] >= 1 && [type intValue] <= 4) {
        //音频
        //收集歌曲了
        for (NSDictionary *dictionary in _downedMusicArr) {
            type = [dictionary objectForKey:@"type"];
            if ([type intValue] >= 1 && [type intValue] <= 4) {
                [newMusicArr addObject:dictionary];
            }
        }
        
        NSInteger indexPD = 0;
        if ([newMusicArr containsObject:_selectCurrentMusicDic]) {
            indexPD = [newMusicArr indexOfObject:_selectCurrentMusicDic];
        }
        
        if (_selectCurrentMusicDic.allKeys.count == 0) {
            //第一次
            [[UserManager standerDefult]playMusicWithMusicArray:_downedMusicArr withCurrentIndex:0 withMusicPlayType:_musicPlayType];
        } else if ([_downedMusicArr containsObject:_selectCurrentMusicDic]) {
            int index = (int)[_downedMusicArr indexOfObject:_selectCurrentMusicDic];
            //当前页面播放
            [[UserManager standerDefult]playMusicWithMusicArray:_downedMusicArr withCurrentIndex:index withMusicPlayType:_musicPlayType];
        }
    }
    else if ([type intValue] >= 5 && [type intValue] <= 6) {
        //收集歌曲了
        for (NSDictionary *dictionary in _downedMusicArr) {
            type = [dictionary objectForKey:@"type"];
            if ([type intValue] >= 5 && [type intValue] <= 6) {
                [newMusicArr addObject:dictionary];
            }
        }
        
        NSInteger indexPD = 0;
        if ([newMusicArr containsObject:_selectCurrentMusicDic]) {
            indexPD = [newMusicArr indexOfObject:_selectCurrentMusicDic];
        }
        
        //数据类型整理
        NSMutableArray *nArray = [[NSMutableArray alloc]initWithArray:newMusicArr];
        [newMusicArr removeAllObjects];
        for (NSDictionary *dic in nArray) {
            if (_type == MBSpaceDownedMusicType_Downed) {
                NSString *coverPath = [dic objectForKey:@"picture"];
                if ([coverPath hasPrefix:MUSIC_PLAY_Url]) {
                    coverPath = [[coverPath componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                }
                NSString *filePath = [dic objectForKey:@"mp3"];
                if ([filePath hasPrefix:MUSIC_PLAY_Url]) {
                    filePath = [[filePath componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                }
                
                NSDictionary *nDic = @{@"ActivityID":@"0",@"AuditionNum":@"0",@"Capacity":[dic objectForKey:@"size"],@"CollectNum":@"0",@"CoverPath":coverPath,
                                       @"CreateTime":[dic objectForKey:@"date"],@"DownloadNum":@"0",@"FilePath":filePath,@"ID":[dic objectForKey:@"musicId"],@"PraiseNum":@"0",
                                       @"ProType":@"2",@"Sentiment":[dic objectForKey:@"content"],@"ShareNum":@"0",@"ShowStatus":@"1",@"ShowTitle":[dic objectForKey:@"title"],
                                       @"ShowType":[dic objectForKey:@"type"],@"UserID":[dic objectForKey:@"userId"]};
                [newMusicArr addObject:nDic];
                
            } else if (_type == MBSpaceDownedMusicType_Visit) {
                NSString *coverPath = [dic objectForKey:@"coverPath"];
                if ([coverPath hasPrefix:MUSIC_PLAY_Url]) {
                    coverPath = [[coverPath componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                }
                NSString *filePath = [dic objectForKey:@"url"];
                if ([filePath hasPrefix:MUSIC_PLAY_Url]) {
                    filePath = [[filePath componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                }
                
                NSDictionary *nDic = @{@"ActivityID":@"0",@"AuditionNum":@"0",@"Capacity":[dic objectForKey:@"size"],@"CollectNum":@"0",@"CoverPath":coverPath,
                                       @"CreateTime":[dic objectForKey:@"date"],@"DownloadNum":@"0",@"FilePath":filePath,@"ID":[dic objectForKey:@"fileID"],@"PraiseNum":@"0",
                                       @"ProType":@"2",@"Sentiment":[dic objectForKey:@"sentiment"],@"ShareNum":@"0",@"ShowStatus":@"1",@"ShowTitle":[dic objectForKey:@"title"],
                                       @"ShowType":[dic objectForKey:@"type"],@"UserID":[dic objectForKey:@"userId"]};
                [newMusicArr addObject:nDic];
            }

          
        }
        
        NSString *idStr ;
        if (manager.audioPlayerType != AudioPLayerType_Qinzix) {
            //初次进入
            idStr = @"";
            manager.audioPlayerType = AudioPLayerType_Qinzix;
        } else {
            //2次进入
            NSInteger selectIndex = manager.selectMusicIndex;
            NSArray *arr = manager.musicArr;
            Music *dics = [arr objectAtIndex:selectIndex];
            idStr = [NSString stringWithFormat:@"%@",dics.ID];
        }
        [manager setSelectMusicIndex:indexPD];
        [manager.musicArr removeAllObjects];
        [manager.musicArr addObjectsFromArray:[manager onTurnArrayFormQingZiXiuArray:newMusicArr]];
        [manager.qinzixiuArr removeAllObjects];
        [manager.qinzixiuArr addObjectsFromArray:newMusicArr];
        
        if (ISIPAD) {
            MBDetailViewForIpadController*childShowVC = [[MBDetailViewForIpadController alloc] init];
            [childShowVC.dataAllArr addObjectsFromArray:newMusicArr];
            childShowVC.selectMusicID = idStr;
            [self.navigationController pushViewController:childShowVC animated:YES];
            return;

        }
        MBDetailViewController *childShowVC = [[MBDetailViewController alloc] init];
        [childShowVC.dataAllArr addObjectsFromArray:newMusicArr];
        childShowVC.selectMusicID = idStr;
        [self.navigationController pushViewController:childShowVC animated:YES];
    }
    
}

//删除
- (void)onSelctItemForMoreDeleteMusic:(SharePLayerView *)view
{
    NSLog(@"删除");
    if (_selectCurrentMusicDic) {
//        UserModel *model = [UserManager standerDefult].userModel;
//        if (!model.UserID) {
//            MBLoginController *registerLastVC = [[MBLoginController alloc] init];
//            registerLastVC.formBaseViewCtrl = NSStringFromClass([self class]);
//            [self.navigationController pushViewController:registerLastVC animated:YES];
//            return;
//        }
        
        if ([_downedMusicArr containsObject:_selectCurrentMusicDic]) {
            NSUInteger index = [_downedMusicArr indexOfObject:_selectCurrentMusicDic];
            [_downedMusicArr removeObject:_selectCurrentMusicDic];
            [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            
            //同步
            FMManageObject *manager = [FMManageObject standerDefault];
            if (self.type == MBSpaceDownedMusicType_Downed) {
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if (![_selectCurrentMusicDic.allKeys containsObject:@"userPic"]) {
                    //音频
                    [manager deleteCunstomFileID:[_selectCurrentMusicDic objectForKey:@"fileID"]];
                    if ([fileManager fileExistsAtPath:[_selectCurrentMusicDic objectForKey:@"url"]]) {
                        [fileManager removeItemAtPath:[_selectCurrentMusicDic objectForKey:@"url"] error:NULL];
                    }
                    NSArray *musicArr = [manager onSelectCustomMusicFileCount];
                    [[UserManager standerDefult].downedMusicArr removeAllObjects];
                    [[UserManager standerDefult].downedMusicArr addObjectsFromArray:musicArr];
                } else {
                    [manager deleteByLocalParentChildShowFilID:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"id"]]];
                    if ([fileManager fileExistsAtPath:[NSString stringWithFormat:@"qzx_%@.mp3",[_selectCurrentMusicDic objectForKey:@"title"]]]) {
                        [fileManager removeItemAtPath:[NSString stringWithFormat:@"qzx_%@.mp3",[_selectCurrentMusicDic objectForKey:@"title"]] error:NULL];
                    }
                    
                }
            }
            else if (self.type == MBSpaceDownedMusicType_Visit) {
                [manager deleteByMusicPlayForRecentFileID:[_selectCurrentMusicDic objectForKey:@"fileID"]];
            }
            
            
            
            _selectCurrentMusicDic = nil;
        }
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _downedMusicArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //歌曲
    static NSString *cellID = @"Collection_Music_Cell";
    MBSpaceCollectionMusicCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MBSpaceCollectionMusicCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.delegate = self;
    }
    //是否隐藏更多按钮
    cell.isHideMoewBt = NO;
    [cell onCompileCellForLayout:self.isCompiling WithAllSelct:self.isAllSelcting];
    cell.orientation = self.orientation;
    cell.isShowDowned = YES;
    
    
    //value
    if (self.type == MBSpaceDownedMusicType_Downed) {
        if (_downedMusicArr.count > indexPath.row) {
            cell.downedDic = [_downedMusicArr objectAtIndex:indexPath.row];
        }
    }
    else if (self.type == MBSpaceDownedMusicType_Visit) {
        if (_downedMusicArr.count > indexPath.row) {
            NSDictionary *dic = [_downedMusicArr objectAtIndex:indexPath.row];
            cell.downedDic = dic;
            NSString *idStr = [dic objectForKey:@"fileID"];
            if ([_fileIDArr containsObject:idStr]) {
                cell.isShowDowned = YES;
            } else {
                cell.isShowDowned = NO;
            }
        }
    }
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100*PERCEN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"*******");
    //编译状态不能点击
    if (!self.isCompiling) {
        NSDictionary *dic = [_downedMusicArr objectAtIndex:indexPath.row];
        NSString *type = [dic objectForKey:@"type"];
        NSMutableArray *newMusicArr = [[NSMutableArray alloc]init];
        UserManager *manager = [UserManager standerDefult];
        
        if ([type intValue] >= 1 && [type intValue] <= 4) {
            //音频
            //收集歌曲了
            for (NSDictionary *dictionary in _downedMusicArr) {
                type = [dictionary objectForKey:@"type"];
                if ([type intValue] >= 1 && [type intValue] <= 4) {
                    [newMusicArr addObject:dictionary];
                }
            }
            
            NSInteger indexPD = 0;
            if ([newMusicArr containsObject:dic]) {
                indexPD = [newMusicArr indexOfObject:dic];
            }
            
            if ([UserManager standerDefult].musicPlayType != _musicPlayType) {
                //第一次
                [[UserManager standerDefult]playMusicWithMusicArray:newMusicArr withCurrentIndex:indexPD withMusicPlayType:_musicPlayType];
            }
            else if ([UserManager standerDefult].selectMusicIndex != indexPD) {
                //当前页面播放
                [[UserManager standerDefult]playMusicWithMusicArray:newMusicArr withCurrentIndex:indexPD withMusicPlayType:_musicPlayType];
            } else {
                //2次点击进入播放页面
                if ([UserManager standerDefult].musicArr.count > 0) {
                    //歌曲列表没歌曲 无需进入
                    UserManager *manager = [UserManager standerDefult];
                    [manager setSelectMusicIndex:indexPD];
                    if (manager.audioPlayerType != AudioPLayerType_YinPin) {
                        [manager setIsPlaying:NO];
                        [manager setAudioPlayerType:AudioPLayerType_YinPin];
                    } else {
                        [manager setIsPlaying:YES];
                    }
                    
                    if (ISIPAD) {
                        MBSongDetailForIpadController*song=[[MBSongDetailForIpadController alloc]init];
                        [self.navigationController pushViewController:song animated:YES];
                        return;
                    }
                    
                    MBSongDetailController *song = [[MBSongDetailController alloc]init];
                    [self.navigationController pushViewController:song animated:YES];
                }
                
            }
    
         
        }
        else if ([type intValue] >= 5 && [type intValue] <= 6) {
            //收集歌曲了
            for (NSDictionary *dictionary in _downedMusicArr) {
                type = [dictionary objectForKey:@"type"];
                if ([type intValue] >= 5 && [type intValue] <= 6) {
                    [newMusicArr addObject:dictionary];
                }
            }
            
            NSInteger indexPD = 0;
            if ([newMusicArr containsObject:dic]) {
                indexPD = [newMusicArr indexOfObject:dic];
            }
            
            //数据类型整理
            NSMutableArray *nArray = [[NSMutableArray alloc]initWithArray:newMusicArr];
            [newMusicArr removeAllObjects];
            for (NSDictionary *dic in nArray) {
                if (_type == MBSpaceDownedMusicType_Downed) {
                    NSString *coverPath = [dic objectForKey:@"picture"];
                    if ([coverPath hasPrefix:MUSIC_PLAY_Url]) {
                        coverPath = [[coverPath componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                    }
                    NSString *filePath = [dic objectForKey:@"mp3"];
                    if ([filePath hasPrefix:MUSIC_PLAY_Url]) {
                        filePath = [[filePath componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                    }
                    
                    NSString *userPic = [dic objectForKey:@"userPic"];
                    if ([userPic hasPrefix:MUSIC_PLAY_Url]) {
                        userPic = [[userPic componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                    }
                    
                    NSDictionary *nDic = @{@"ActivityID":@"0",@"AuditionNum":@"0",@"Capacity":[dic objectForKey:@"size"],@"CollectNum":@"0",@"CoverPath":coverPath,
                                           @"CreateTime":[dic objectForKey:@"date"],@"DownloadNum":@"0",@"FilePath":filePath,@"ID":[dic objectForKey:@"musicId"],@"PraiseNum":@"0",
                                           @"ProType":@"2",@"Sentiment":[dic objectForKey:@"content"],@"ShareNum":@"0",@"ShowStatus":@"1",@"ShowTitle":[dic objectForKey:@"title"],
                                           @"ShowType":[dic objectForKey:@"type"],@"UserID":[dic objectForKey:@"userId"],@"FaceImg":userPic,@"NickName":[dic objectForKey:@"userNick"]};
                    [newMusicArr addObject:nDic];
                }
                else if (_type == MBSpaceDownedMusicType_Visit) {
                    NSString *coverPath = [dic objectForKey:@"coverPath"];
                    if ([coverPath hasPrefix:MUSIC_PLAY_Url]) {
                        coverPath = [[coverPath componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                    }
                    NSString *filePath = [dic objectForKey:@"url"];
                    if ([filePath hasPrefix:MUSIC_PLAY_Url]) {
                        filePath = [[filePath componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                    }
                    
                    NSString *userPic = [dic objectForKey:@"userPic"];
                    if ([userPic hasPrefix:MUSIC_PLAY_Url]) {
                        userPic = [[userPic componentsSeparatedByString:MUSIC_PLAY_Url] lastObject];
                    }
                    
                    NSDictionary *nDic = @{@"ActivityID":@"0",@"AuditionNum":@"0",@"Capacity":[dic objectForKey:@"size"],@"CollectNum":@"0",@"CoverPath":coverPath,
                                           @"CreateTime":[dic objectForKey:@"date"],@"DownloadNum":@"0",@"FilePath":filePath,@"ID":[dic objectForKey:@"fileID"],@"PraiseNum":@"0",
                                           @"ProType":@"2",@"Sentiment":[dic objectForKey:@"sentiment"],@"ShareNum":@"0",@"ShowStatus":@"1",@"ShowTitle":[dic objectForKey:@"title"],
                                           @"ShowType":[dic objectForKey:@"type"],@"UserID":[dic objectForKey:@"userId"],@"FaceImg":userPic,@"NickName":[dic objectForKey:@"userNick"]};
                    [newMusicArr addObject:nDic];
                }
              
            }
            
            NSString *idStr ;
            if (manager.audioPlayerType != AudioPLayerType_Qinzix) {
                //初次进入
                idStr = @"";
                manager.audioPlayerType = AudioPLayerType_Qinzix;
            } else {
                //2次进入
                NSInteger selectIndex = manager.selectMusicIndex;
                NSArray *arr = manager.musicArr;
                Music *dics = [arr objectAtIndex:selectIndex];
                idStr = [NSString stringWithFormat:@"%@",dics.ID];
            }
            [manager setSelectMusicIndex:indexPD];
            [manager.musicArr removeAllObjects];
            [manager.musicArr addObjectsFromArray:[manager onTurnArrayFormQingZiXiuArray:newMusicArr]];
            [manager.qinzixiuArr removeAllObjects];
            [manager.qinzixiuArr addObjectsFromArray:newMusicArr];
            
            if (ISIPAD) {
                MBDetailViewForIpadController *childShowVC = [[MBDetailViewForIpadController alloc] init];
                [childShowVC.dataAllArr addObjectsFromArray:newMusicArr];
                childShowVC.selectMusicID = idStr;
                [self.navigationController pushViewController:childShowVC animated:YES];
                return;
            }
            MBDetailViewController *childShowVC = [[MBDetailViewController alloc] init];
            [childShowVC.dataAllArr addObjectsFromArray:newMusicArr];
            childShowVC.selectMusicID = idStr;
            [self.navigationController pushViewController:childShowVC animated:YES];
        }
        
      
        [_selectCurrentMusicDic removeAllObjects];
        [_selectCurrentMusicDic addEntriesFromDictionary:dic];

    }
    else {
        //编辑状态就选中勾选
        MBSpaceCollectionMusicCell *cell = (MBSpaceCollectionMusicCell *)[tableView cellForRowAtIndexPath:indexPath];
        if ([cell isKindOfClass:[MBSpaceCollectionMusicCell class]]) {
            [cell onGouXuanToSelectAction:cell.selectBt];
        }
    }
    
}

@end
